package com.self.cloudmall.sso.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.self.cloudmall.common.constant.SsoConstant;
import com.self.cloudmall.common.dto.LoginUserDto;
import com.self.cloudmall.common.enumm.ResultErrorEum;
import com.self.cloudmall.common.utils.R;
import com.self.cloudmall.sso.client.MemberClient;
import com.self.cloudmall.sso.service.LoginService;
import com.self.cloudmall.sso.vo.LoginUserVo;
import com.self.cloudmall.sso.vo.UserRegistVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @version v1.0
 * @ClassName: PageController
 * @Description:
 * @Author: M10003729
 */
@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private MemberClient memberClient;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(SsoConstant.LOGIN_USER);
        if (attribute != null){
            return "http://cloudmall.com";
        }
        return "login";
    }


    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone){
      if (StringUtils.isEmpty(phone)){
          return R.error("手机号或验证码不能为空");
      }
      return loginService.sendCode(phone);
    }

    @PostMapping("/sso/regist")
    public String regist(@Validated UserRegistVo registVo, BindingResult result, Model model){
        if (result.hasErrors()){
            Map<String, String> map = Maps.newHashMap();
            for (FieldError error : result.getFieldErrors()){
                map.put(error.getField(),error.getDefaultMessage());
            }
            model.addAttribute("errors",map);
            return "register";
        }
        Map<String,String> errorMap = Maps.newHashMap();
        //短信验证码校验真实平台使用，把这块打开
        /*String value = (String) redisTemplate.opsForValue().get(SsoConstant.REDIS_VALID_CODE_KEY + phone);
        if (!org.springframework.util.StringUtils.isEmpty(value)){
            String[] split = value.split("_");
            if (!registVo.getCode().equalsIgnoreCase(split[0])){
                errorMap.put("code","验证码错误");
            }
        }else{
            errorMap.put("code","验证码失效，请重试");
        }*/
        R regist = memberClient.regist(registVo);
        if (!regist.isSuccess()){
            Integer code = (Integer) regist.get("code");
            if (code != null && (code == ResultErrorEum.USERNAME_REPEAT.getCode() ||
                    code == ResultErrorEum.MOBILE_REPEAT.getCode())){
                if (code == ResultErrorEum.USERNAME_REPEAT.getCode()){
                    errorMap.put("username",(String) regist.get("msg"));
                }
                if (code == ResultErrorEum.MOBILE_REPEAT.getCode()){
                    errorMap.put("phone",(String) regist.get("msg"));
                }
            }else{
                errorMap.put("msg",(String) regist.get("msg"));
            }
            model.addAttribute("errors",errorMap);
            return "register";
        }

        return "login";
    }

    @PostMapping("/sso/login")
    public String login(@Validated LoginUserVo loginUserVo, BindingResult result,RedirectAttributes redirect, HttpSession session){
        if (result.hasErrors()){
            redirect.addFlashAttribute("msg",result.getFieldError().getDefaultMessage());
            return "redirect:http://sso.cloudmall.com/login.html";
        }
        R r = loginService.login(loginUserVo);
        if (!r.isSuccess()){
            redirect.addFlashAttribute("msg",(String)r.get("msg"));
            return "redirect:http://sso.cloudmall.com/login.html";
        }
        LoginUserDto data = JSONObject.parseObject(JSONObject.toJSONString(r.getData()),LoginUserDto.class);
        session.setAttribute(SsoConstant.LOGIN_USER,data);
        if (StringUtils.isNotEmpty(loginUserVo.getOriginUrl())){
            return "redirect:"+loginUserVo.getOriginUrl();
        }
        return "redirect:http://cloudmall.com";
    }

    /**
     * @Title: 社交登录回调接口
     * @Description:
     * @Param [code]
     * @Return java.lang.String
     * @Author M10003729
     */
    @GetMapping("/sso/success")
    public String socialSuccess(@RequestParam("code") String code, RedirectAttributes redirect, HttpSession session){
         R r = loginService.socialLogin(code);
         if (!r.isSuccess()){
             redirect.addFlashAttribute("msg",(String)r.get("msg"));
             return "redirect:http://sso.cloudmall.com/login.html";
         }
        LoginUserDto data = JSONObject.parseObject(JSONObject.toJSONString(r.getData()),LoginUserDto.class);
        session.setAttribute(SsoConstant.LOGIN_USER,data);
         return "redirect:http://cloudmall.com";
    }
}
